package com.kaikai.edu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author yujiankai
 * @Description redis工具类
 * @date 2021/12/2 15:33
 */
@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @param key 
     * @return java.lang.Object
     * @Author yujiankai
     * @Description 普通缓存获取
     * @date 2021/12/2 15:35
     */
    public Object get(String key){
            return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * @param key
     * @return boolean
     * @return Object
     * @Author yujiankai
     * @Description 普通缓存添加 成功返回true
     * @date 2021/12/2 15:36
     */
    public boolean set(String key,Object object){
        try {
            redisTemplate.opsForValue().set(key, object);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key
	 * @param value
	 * @param time 
     * @return boolean
     * @Author yujiankai
     * @Description 普通缓存中添加数据 设置过期时间
     * @date 2021/12/2 15:40
     */
    public boolean set(String key, Object value, long time,TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, timeUnit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     */

    public boolean expire(String key, long time,TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param key
     * @return boolean
     * @Author yujiankai
     * @Description 判断是否有该key
     * @date 2021/12/2 16:06
     */
    public boolean hasKey(String key){
        return key == null ? null : redisTemplate.hasKey(key);
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */

    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
}
